package Dao.DaoImpl;

import Dao.StudentDao;
import Utils.JDBCUtils;
import domain.Student;
import domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public void addStudent(Student student) {
        System.out.println("addStudent"+student);
        String sql = "insert into student values(?,?,?,?,?)";

        template.update(sql,student.getStunum(),student.getName(),student.getSex(),student.getClasses(),student.getDormnum());
    }

    @Override
    public List<Student> fuzzyQueryStudent(HashMap<String, String> map) {
        String sql = "select * from student where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        Set<String> set = map.keySet();
        List<Object> params = new ArrayList<Object>();
        for (String key : set) {
            String value = map.get(key);

            //判断value是否有值
            if(value!=null && !"".equals(value)){
                //有值就拼接
                sb.append(" and "+key+" like ?");
                params.add("%"+value+"%");//上面 ? 的值
            }
        }
        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<Student>(Student.class),params.toArray());
    }

    @Override
    public List<Student> listStudent() {
        String sql ="select * from student";
        return template.query(sql,new BeanPropertyRowMapper<Student>(Student.class));
    }


    @Override
    public List<Student> findStudentByStunum(String stunum) {
        String sql ="select * from student where stunum=?";

        return template.query(sql,new BeanPropertyRowMapper<Student>(Student.class),stunum);
    }

    @Override
    public void updateStudent(Student student) {
        String sql = "update student set name=?,sex=?,classes=?,dormnum=? where stunum=?";
        template.update(sql,student.getName(),student.getSex(),student.getClasses(),student.getDormnum(),student.getStunum());
    }

    @Override
    public void deleteStudentByStunum(String stunum) {
        String sql ="delete from student where stunum=?";
        template.update(sql,stunum);
    }


}
